import time
import smtplib
import common
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

 
###################################################################
# Post Class
###################################################################
class Post:
   def __init__(self, city, section, query, price):
      
      # attributes
      self.Id = [] 
      self.date = [] 
      self.http = []
      self.title = []
      self.price = 0 
      self.location = []
      self.hasPic = 0 
      self.queryId = 0
      self.epoch = 0
      self.emailed = 0
      self.emailMsg = []
      self.city = city
      self.section = section
      self.query = query
      self.jpgs = []

      # constraints
      self.priceThreshold = price 

   def createPostStr(self):
      self.emailMsg = "Post.city: %s\n" % self.city 
      self.emailMsg = self.emailMsg + "Post.section: %s\n" % self.section 
      self.emailMsg = self.emailMsg + "Post.query: %s\n" % self.query 
      self.emailMsg = self.emailMsg + "Post.Id: %s\n" % self.Id 
      self.emailMsg = self.emailMsg + "Post.date: %s\n" % self.date 
      self.emailMsg = self.emailMsg + "Post.http: %s\n" % self.http 
      self.emailMsg = self.emailMsg + "Post.title: %s\n" % self.title 
      self.emailMsg = self.emailMsg + "Post.price: %s\n" % self.price 
      self.emailMsg = self.emailMsg + "Post.location: %s\n" % self.location 
      self.emailMsg = self.emailMsg + "Post.hasPic: %s\n" % self.hasPic 
      self.emailMsg = self.emailMsg + "Post.queryId: %s\n" % self.queryId 
      self.emailMsg = self.emailMsg + "Post.epoch: %s\n" % self.epoch 
      self.emailMsg = self.emailMsg + "Post.emailed: %s\n" % self.emailed 
      self.emailMsg = self.emailMsg + "Post.priceThreshold: %s\n" % self.priceThreshold 
      for i in range(len(self.jpgs)):
         self.emailMsg = self.emailMsg + "Post.jpgs[%d]: %s\n" % (i, self.jpgs[i])


   def _print(self):
      common.logMsg("----------Post._print-------------")
      self.createPostStr()
      common.logMsg(self.emailMsg)

###################################################################
# Query Class
###################################################################
class Query:
   def __init__(self):
      self.Posts = []
      self.length = 0

   def _print(self):
      common.logMsg("Query len: " + str(self.length))
      for i in self.Posts:
         i._print()

   def isUnique(self, ppost):
      unique = 1
      for i in self.Posts:
         if i.Id == ppost.Id:
            unique = 0
            break 
      return unique
   
   def hasPrice(self, ppost):
      if ppost.price > 0 and \
         ppost.price < ppost.priceThreshold:
         return 1
      else:
         return 0

   def twoDaysOld(self, ppost):
      sec = 172800   # two days of seconds
      now = int(round(time.time()))
      if ppost.epoch > (now - sec):
         return 1 
      else:
         return 0   

   def populatePictures(self, post):
      postMsg = common.requestURL(post.http)
      if postMsg == []:
         print "no post was returned"
         return

      infile = open("postMsg.html", "w")
      infile.write(postMsg)
      infile.close()

      infile = open("postMsg.html", "r")
      line = infile.readline()
      imgsAddr = []
      while(len(line) != 0):
         if "imgList" in line:
#            print "full line:", line
            sp = line.split("[")
            ht = sp[1].split("http://")
            for i in ht:
               if "jpg" in i:
                  imgsAddr.append("http://" + i.split(".jpg")[0] + ".jpg")
         line = infile.readline() 
      infile.close()
     
      cnt = 0 
      for i in imgsAddr:
         img = common.requestURL(i)
         n = post.Id + str(cnt) + ".jpg"
         infile = open(n,"w")
         infile.write(img)
         infile.close()
         cnt = cnt + 1
         post.jpgs.append(n)

   def verifyConstraints(self, post):
#      print "verifyConstraints"
#      post._print()
#      raw_input("stop")
      if self.isUnique(post) != 1:       
#         print "not unique"
         return 0 
      if self.hasPrice(post) != 1:
#         print "no price"
         return 0 
      if post.hasPic != 1:
#         print "no pic"
         return 0
      if self.twoDaysOld(post) != 1:
#         print "too old"
         return 0 

      self.populatePictures(post)
      return 1            
      
   def add(self, post):
#      print "possible post"
#      print post
#      raw_input("pause")
      if self.verifyConstraints(post):
#         post._print()
         self.length = self.length + 1
         post.queryId = self.length
         self.Posts.append(post)
#         raw_input("pause")
     
   def emailQuery(self, smtp_host, from_email, to_email, smtp_username, smtp_password):

      # connect and authenticate to server
      server = smtplib.SMTP(smtp_host)
      server.starttls()
      server.login(smtp_username, smtp_password)

      if server == []:
         print "Error connecting to server\n"
         return

      for i in self.Posts:
         if i.emailed == 0:
            if i.emailMsg == []:
               i.createPostStr()
            textMsg = MIMEText(i.emailMsg)
            msg = MIMEMultipart()
            sub = i.title
            msg['Subject'] = sub 
            msg['From'] = from_email
            msg['To'] = to_email

            for pic in i.jpgs:
               fp = open(pic, 'rb')
               img = MIMEImage(fp.read())
               fp.close()
               # TODO: can delete jps here, after we've emailed them
               msg.attach(img)

            msg.attach(textMsg)
            common.logMsg(textMsg)
            common.logMsg("sending email")
            common.logMsg("from_email:" + from_email)
            common.logMsg("to_email:" + to_email)
            server.sendmail(from_email, [to_email], msg.as_string())
            i.emailed = 1             

      server.quit()
 
